1 /*
2 * Copyright (C) 2012 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.common.hash;
18
19 import com.google.caliper.BeforeExperiment;
20 import com.google.caliper.Benchmark;
21 import com.google.caliper.Param;
22 import com.google.common.hash.HashFunction;
23
24 import java.util.Random;
25
26 /**
27 * Benchmarks for comparing the various {@link HashFunction functions} that we provide.
28 *
29 * <p>Parameters for the benchmark are:
30 * <ul>
31 * <li>size: The length of the byte array to hash.
32 * <li>hashFunctionEnum: The {@link HashFunction} to use for hashing.
33 * </ul>
34 *
35 * @author Kurt Alfred Kluever
36 */
37 public class HashFunctionBenchmark {
38
39 // Use a statically configured random instance for all of the benchmarks
40 private static final Random random = new Random(42);
41
42 @Param({"10", "1000", "100000", "1000000"})
43 private int size;
44
45 @Param HashFunctionEnum hashFunctionEnum;
46
47 private byte[] testBytes;
48
49 @BeforeExperiment void setUp() {
50 testBytes = new byte[size];
51 random.nextBytes(testBytes);
52 }
53
54 @Benchmark int hashFunction(int reps) {
55 HashFunction hashFunction = hashFunctionEnum.getHashFunction();
56 int result = 37;
57 for (int i = 0; i < reps; i++) {
58 result ^= hashFunction.hashBytes(testBytes).asBytes()[0];
59 }
60 return result;
61 }
62 }